import gcoord from "../../miniprogram_npm/gcoord/dist/gcoord";
const dayjs = require("dayjs");
const yearQuarterColumnsList = {
  2019: ["第一季度", "第二季度", "第三季度", "第四季度"],
  2020: ["第一季度", "第二季度", "第三季度", "第四季度"],
  2021: ["第一季度", "第二季度", "第三季度", "第四季度"],
  2022: ["第一季度", "第二季度", "第三季度", "第四季度"],
};
Page({
  data: {
    // 当前的位置
    latitude: "",
    longitude: "",
    markers: [],
    activeIndex: 0, // 默认的产业选择
    mapCtx: null, // 地图实例对象
    tabLists: [
      // "全部",
      "电子信息",
      "数字经济",
      "高端装备制造",
      "生物医药",
      "集成电路",
      "汽车零部件",
      "先进材料",
      "软件服务",
      "航空航天",
    ],
    cardIcons: {
      ratenew: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-xsqy-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-xsqy-xz.png",
      },
      ratereg: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-xszb-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-xszb-xz.png",
      },
      rateper: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-ygrs-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-ygrs-xz.png",
      },
      rateamount: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-sbje-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-sbje-xz.png",
      },
      ratepatent: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-zhuanli-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-zhuanli-xz.png",
      },
      ratelnum: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-sdqy-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-sdqy-xz.png",
      },
      rateloan: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-dkye-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-dkye-xz.png",
      },
      ratefst: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-sdqy-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-sdqy-xz.png",
      },
      ratefstloan: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-shoudai-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-shoudai-xz.png",
      },
      ratetax: {
        default:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-nsje-wxz.png",
        active:
          " https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/cy-nsje-xz.png",
      },
    },
    cardList: [],
    showAll: false, // 是否显示总揽
    selectIndex: "", // 选中展示的卡片
    showEchart: false, // 是否展示echarts
    allData: {}, // echarts展示的数据集合
    distributeList: [], // 分布点数据
    compareValue: "1", // 默认展示同比
    oriEcharts: [], // 同比和环比的原始数据
    device: "",
    region: "", // 区域名称
    showPicker: false, // 展示日期选择框
    showDateValue: "", // 显示的时间
    minDate: "", // 开始时间戳
    nowDate: "", // 当前时间戳
    maxDate: "", // 结束时间戳
    key: "",
    title: "",
    dateType: "month",
    yearList: ["2019", "2020", "2021", "2022"],
    showYearQuarter: false,
    showYear: false,
    showMonth: false,
    yearColumns: [
      {
        values: ["2019", "2020", "2021", "2022"],
        defaultIndex: 3,
      },
    ],
    yearQuarterColumns: [
      {
        values: Object.keys(yearQuarterColumnsList),
        className: "column1",
      },
      {
        values: yearQuarterColumnsList[2022],
        className: "column2",
        defaultIndex: 3,
      },
    ],
    timeType: "month", //日期类型
    time: "", //选择的时间
  },

  // 页面解析完成后执行
  onReady: function () {
    // 步骤一、常见地图实例对象
    this.mapCtx = wx.createMapContext("hotMap");
  },
  onLoad: function (e) {
    // 日期展示倒推2个月
    this.setData({
      showDateValue: dayjs().subtract(2, "month").format("YYYY年MM月"),
      nowDate: new Date(
        dayjs().subtract(2, "month").format("YYYY-MM-DD")
      ).getTime(),
      minDate: new Date(
        dayjs().subtract(7, "month").format("YYYY-MM-DD")
      ).getTime(),
      maxDate: new Date(
        dayjs().subtract(2, "month").format("YYYY-MM-DD")
      ).getTime(),
      time: dayjs().subtract(2, "month").format("YYYYMM"),
    });
    // 判断当前的手机
    const that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform == "devtools") {
          that.setData({
            device: "PC",
          });
        } else if (res.platform == "ios") {
          that.setData({
            device: "IOS",
          });
        } else if (res.platform == "android") {
          that.setData({
            device: "Android",
          });
        }
      },
    });
    // 定位到某个区域（苏州市定位到市政府的位置）
    if (e.region === "苏州市") {
      this.setData({
        latitude: 31.29742,
        longitude: 120.58664,
        region: e.region,
      });
    } else {
      this.setData({
        latitude: e.latitude,
        longitude: e.longitude,
        region: e.region,
      });
    }

    // 设置标题
    wx.setNavigationBarTitle({
      title: this.data.region, //页面标题为路由参数
    });
    // 获取卡片信息
    this.getCardInfos();
  },
  /**
   * methods
   */
  // 获取卡片信息
  async getCardInfos() {
    const params = {
      type:
        this.data.tabLists[this.data.activeIndex] === "全部"
          ? ""
          : this.data.tabLists[this.data.activeIndex],
      region: this.data.region === "苏州市" ? "苏州全市" : this.data.region,
      time: this.data.time,
      timeType: this.data.timeType,
    };
    console.log(params, "获取卡片信息--请求头");
    const { data } = await getApp().globalData.request(
      "/map/queryIndustryIndexByRegion",
      params,
      "POST"
    );
    data.forEach((val) => {
      if (this.data.timeType === "month") {
        val.compare =
          this.data.compareValue === "1" ? val.ratio : val.ringRatio;
      } else {
        val.compare = val.ringRatio;
      }
      val.show = true;
      val.default = this.data.cardIcons[val.key].default;
      val.active = this.data.cardIcons[val.key].active;
    });
    this.setData({
      cardList: data,
    });
    console.log(data, "获取卡片信息--返回信息");
  },

  // 处理卡片对应的点
  async getCardMarkers() {
    if (this.data.timeType === "month") {
      // if (this.data.timeType === "month" && this.data.activeIndex !== 0) {
      // 获取对应的分布点
      await this.getkeyIndustryCount();
      // 初始化markers;
      this.initMarkers();
    }
  },

  // 获取对应的分布点
  async getkeyIndustryCount() {
    const params = {
      type: this.data.tabLists[this.data.activeIndex],
      region: this.data.region === "苏州市" ? "苏州全市" : this.data.region,
      tab: this.data.key,
    };
    console.log(params, "请求卡片的参数");
    const { data } = await getApp().globalData.request(
      "/map/queryPointByRegionAndIndustryAndTab",
      params,
      "POST"
    );
    console.log(data, "卡片的点");
    this.setData({
      distributeList: data,
    });
  },

  // 初始化点标记
  initMarkers() {
    const markers = [];
    console.log(this.data.distributeList);
    this.data.distributeList.forEach((val, index) => {
      const zuobiao = this.transMarker1([val.longitude, val.latitude]);
      const longitude = zuobiao[0];
      const latitude = zuobiao[1];

      if (val) {
        markers.push({
          id: index,
          latitude: latitude,
          longitude: longitude,
          width: 18,
          height: 23,
          iconPath:
            "https://zx-1311146360.cos.ap-shanghai.myqcloud.com/version01/location-cyhot1.png",
          label: {
            id: index,
            content: `${this.data.key === "rateloan" ? "" : val.count}`,
            fontSize: 10,
            borderWidth: 1,
            borderColor: "",
            color: "#ED7D77",
            textAlign: "center",
            anchorX: this.data.device === "IOS" ? 0 : -4,
            anchorY: -2,
            corpList: val.corpList,
          },
          callout: {
            content: `${val.corpList[0].d2CorpName}${
              val.corpList.length > 0
                ? "等" + val.corpList.length + "家企业"
                : ""
            },点击查看`,
            color: "#ffffff",
            bgColor: "#505d58", //需要6位的色值有效
            fontSize: 14,
            borderRadius: 2,
            padding: 5,
            display: "BYCLICK", //'BYCLICK':点击显示; 'ALWAYS':常显
          },
        });
      }
    });
    this.setData({
      markers: markers,
    });
  },
  // 坐标系转化
  transMarker(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.GCJ02, // 当前坐标系
      gcoord.BD09 // 目标坐标系
    );
    return resae;
  },
  markerCalloutTap() {
    console.log(1);
  },
  markerClick(e) {
    console.log(e.detail.markerId);
    console.log(this.data.markers[e.detail.markerId]);
    if (this.data.markers[e.detail.markerId].label.corpList.length > 1) {
      // 跳转到列表页面
      wx.navigateTo({
        url: `../../packageB/pages/businesses/businesses?businesses=${JSON.stringify(
          this.data.markers[e.detail.markerId].label.corpList
        )}`,
      });
    } else {
      // 跳转到详情页面
      wx.navigateTo({
        url: `/pages/mapDetail/mapDetail?corpKey=${
          this.data.markers[e.detail.markerId].label.corpList[0].corpKey
        }&latitude=${
          this.data.markers[e.detail.markerId].label.corpList[0].latitude
        }&longitude=${
          this.data.markers[e.detail.markerId].label.corpList[0].longitude
        }`,
      });
    }
  },
  // 切换日期类型
  changeDate(e) {
    const type = e.currentTarget.dataset.type;
    if (this.data.timeType === type) return;
    switch (type) {
      case "year":
        this.setData({
          timeType: "year",
          time: "2022",
          showDateValue: "2022年",
        });
        break;
      case "quarter":
        this.setData({
          timeType: "quarter",
          time: "202204",
          showDateValue: "2022年第4季度",
        });
        break;
      case "month":
        // 日期展示倒推2个月
        this.setData({
          showDateValue: dayjs().subtract(2, "month").format("YYYY年MM月"),
          time: dayjs().subtract(2, "month").format("YYYYMM"),
          timeType: "month",
        });
        break;
      default:
        break;
    }
    // 获取卡片信息
    this.allCards();
    this.setData({});
    this.getCardInfos();
  },
  // 查看某个卡片
  clickCard(e) {
    if (this.data.showAll) {
      // 总揽情况下点击卡片，打开图表层
      this.initDatas();
    } else {
      // 非总揽情况下点击卡片
      this.setData({
        selectIndex: e.currentTarget.dataset.index,
        showAll: true,
      });
      this.data.cardList.forEach((val, index) => {
        if (e.currentTarget.dataset.index !== index) {
          val.show = false;
        }
      });
      this.setData({
        cardList: this.data.cardList,
      });
      // 获取卡片对应的echarts数据
      this.setData({
        key: e.currentTarget.dataset.key,
        title: e.currentTarget.dataset.title,
      });
      this.initEchartInfos();
      // 获取卡片对应的点
      this.getCardMarkers();
    }
  },
  // 顶部的tab产业切换
  tabTuijian(e) {
    this.allCards();
    this.setData({
      activeIndex: e.detail.index,
    });
    // 获取对应的卡片信息
    this.getCardInfos();
  },
  // 总览
  allCards() {
    this.data.cardList.forEach((val) => {
      val.show = true;
    });
    this.setData({
      cardList: this.data.cardList,
      selectIndex: "",
      showAll: false,
    });
    // 清除地图上的点markers
    this.mapCtx.addMarkers({
      clear: true,
      markers: [],
    });
  },
  // 返回到中心点
  locationBack() {
    this.mapCtx.moveToLocation({
      longitude: this.data.longitude,
      latitude: this.data.latitude,
    });
  },
  // 关闭图表
  onClickHide() {
    this.setData({
      showEchart: false,
    });
  },
  // 中心点坐标转化
  transMarker1(item) {
    const resae = gcoord.transform(
      [item[0], item[1]],
      gcoord.BD09, // 当前坐标系
      gcoord.GCJ02 // 目标坐标系
    );
    return resae;
  },
  // 同比环比切换
  tongOrhuan(e) {
    if (e.currentTarget.dataset.id === this.data.compareValue) return;
    this.setData({
      compareValue: e.currentTarget.dataset.id,
    });
    this.data.cardList.forEach((ped) => {
      ped.compare =
        e.currentTarget.dataset.id === "1" ? ped.ratio : ped.ringRatio;
    });
    this.setData({
      cardList: this.data.cardList,
    });
    if (this.data.showAll) {
      // 获取卡片对应的echarts数据
      this.initEchartInfos();
      // 获取卡片对应的点
      this.getCardMarkers();
    }
  },
  // 获取卡片对应的echarts数据
  async initEchartInfos(item) {
    const params = {
      type:
        this.data.tabLists[this.data.activeIndex] === "全部"
          ? ""
          : this.data.tabLists[this.data.activeIndex],
      region: this.data.region === "苏州市" ? "苏州全市" : this.data.region,
      tab: this.data.key,
      time: this.data.time,
      timeType: this.data.timeType,
    };
    console.log(params, "请求echarts的参数");
    const { data } = await getApp().globalData.request(
      "/map/querySameByRegionAndIndustryAndTab",
      params,
      "POST"
    );
    console.log(data, "echarts返回数据");
    // 处理接口返回echarts数据（分同比和环比的情况）
    data.title = this.data.title;
    // 保留echarts原始数据
    this.setData({
      oriEcharts: data,
    });
    this.initDatas();
  },
  // 关闭日期选择
  hideYear() {
    this.setData({
      showYear: false,
    });
  },
  // 关闭日期选择
  hideYearQuarter() {
    this.setData({
      showYearQuarter: false,
    });
  },
  // 关闭日期选择
  hideMonth() {
    this.setData({
      showMonth: false,
    });
  },
  // 打开日期选择
  openDate(e) {
    switch (e.currentTarget.dataset.type) {
      case "year":
        this.setData({
          showYear: true,
        });
        break;
      case "quater":
        this.setData({
          showYearQuarter: true,
        });
        break;
      case "month":
        this.setData({
          showMonth: true,
        });
        break;
      default:
        break;
    }
  },
  // 处理月选择的日期（月）
  goSelect(e) {
    this.setData({
      showDateValue: dayjs(e.detail).format("YYYY年MM月"),
      time: dayjs(e.detail).format("YYYYMM"),
      showMonth: false,
      timeType: "month",
    });
    // 获取卡片信息
    this.allCards();
    this.setData({});
    this.getCardInfos();
  },
  // 处理echarts数据
  initDatas() {
    if (this.data.oriEcharts.length === 0) return;
    if (this.data.timeType === "month") {
      const res = {
        years:
          this.data.compareValue === "1"
            ? this.data.oriEcharts.legendList
            : this.data.oriEcharts.legendList.slice(
                this.data.oriEcharts.legendList.length - 1,
                this.data.oriEcharts.legendList.length
              ),
        xData: this.data.oriEcharts.timeList,
        yData:
          this.data.compareValue === "1"
            ? this.data.oriEcharts.dataList
            : this.data.oriEcharts.dataList.slice(
                this.data.oriEcharts.legendList.length - 1,
                this.data.oriEcharts.legendList.length
              ),
        title: `${this.data.oriEcharts.title}${
          this.data.compareValue === "1" ? "同比情况" : "环比情况"
        }`,
        type: this.data.compareValue === "1" ? "bar" : "line",
      };
      this.setData({
        showEchart: true,
        allData: res,
      });
    } else {
      const res = {
        years: [],
        xData: this.data.oriEcharts.timeList,
        yData:
          this.data.compareValue === "1"
            ? this.data.oriEcharts.dataList
            : this.data.oriEcharts.dataList.slice(
                this.data.oriEcharts.legendList.length - 1,
                this.data.oriEcharts.legendList.length
              ),
        title: this.data.oriEcharts.title + "对比情况",
        type: "bar",
      };
      this.setData({
        showEchart: true,
        allData: res,
      });
    }
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    console.log(event.detail, "event.detail");
    picker.setColumnValues(1, yearQuarterColumnsList[value[0]]);
  },
  goYear(event) {
    this.setData({
      showYear: false,
      timeType: "year",
      time: event.detail.value[0],
      showDateValue: `${event.detail.value[0]}年`,
    });
    // 获取卡片信息
    this.allCards();
    this.setData({});
    this.getCardInfos();
  },
  goYearQuarter(event) {
    switch (event.detail.value[1]) {
      case "第一季度":
        this.setData({
          showYearQuarter: false,
          time: event.detail.value[0] + "01",
          timeType: "quarter",
          showDateValue: `${event.detail.value[0]}年第1季度`,
        });
        break;
      case "第二季度":
        this.setData({
          showYearQuarter: false,
          time: event.detail.value[0] + "02",
          timeType: "quarter",
          showDateValue: `${event.detail.value[0]}年第2季度`,
        });
        break;
      case "第三季度":
        this.setData({
          showYearQuarter: false,
          time: event.detail.value[0] + "03",
          timeType: "quarter",
          showDateValue: `${event.detail.value[0]}年第3季度`,
        });
        break;
      case "第四季度":
        this.setData({
          showYearQuarter: false,
          time: event.detail.value[0] + "04",
          timeType: "quarter",
          showDateValue: `${event.detail.value[0]}年第4季度`,
        });
        break;
      default:
        break;
    }
    // 获取卡片信息
    this.allCards();
    this.setData({});
    this.getCardInfos();
  },
  openYearQuarter() {
    this.setData({
      showPicker: true,
      showYearQuarter: true,
    });
  },
});
